package com.elitel.common.utils;

import java.util.concurrent.*;

/**
 * @author mulis
 */
public class ThreadPoolUtils {

    /**
     * 线程池,且保证CPU内核间可见
     */
    public static volatile ThreadPoolExecutor threadPool;

    public static ThreadPoolExecutor getThreadPool() {

        // 双检锁
        if (threadPool != null) {
            return threadPool;
        } else {
            synchronized (ThreadPoolUtils.class) {
                if (threadPool == null) {
                    // 获取CPU核心数量
                    int corePoolSize = Runtime.getRuntime().availableProcessors() + 1;
                    threadPool = new ThreadPoolExecutor(corePoolSize, corePoolSize * 2 + 1, 60, TimeUnit.SECONDS,
                            new LinkedBlockingQueue<>(200), new ThreadPoolExecutor.CallerRunsPolicy());
                }
                return threadPool;
            }
        }
    }

    /**
     * 无返回值直接执行
     *
     * @param runnable
     */
    public static void execute(Runnable runnable) {
        getThreadPool().execute(runnable);
    }

    /**
     * 返回值直接执行
     *
     * @param callable
     */
    public static <T> Future<T> submit(Callable<T> callable) {
        return getThreadPool().submit(callable);
    }

    /**
     * 关闭线程池
     */
    public static void shutdown() {
        getThreadPool().shutdown();
    }
}
